package com.hzgj.bcl.soa.controller.logic;

import com.hzgj.bcl.soa.collector.Collectors;
import com.hzgj.bcl.soa.collector.JmxCollector;
import com.hzgj.bcl.soa.command.CommandsInitializer;
import com.hzgj.bcl.soa.command.RegistryCommand;
import com.hzgj.bcl.soa.registry.Provider;
import com.hzgj.bcl.soa.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * Created by warning5 on 2017/3/17.
 */
public class ServiceDetailLogic implements PageLogic {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public List<String> getPages() {
        return Arrays.asList("service-detail");
    }

    @Override
    public void handle(HttpServletRequest request, Model model) {
        String service = request.getParameter("service");
        model.addAttribute("service", service);
        RegistryCommand soaCommand = CommandsInitializer.getCommand(CommandsInitializer.REG_COMMAND);
        Collection<Provider> providers = soaCommand.getProviders(service);
        providers.forEach(provider -> {
            String[] address = provider.getAddress().split(":");
            JmxCollector jmxCollector = Collectors.getCollector(address[0], provider.getJmxPort());
            try {
                provider.setBizCount(Long.parseLong(jmxCollector.invokeWithoutParam(Constants.getRpcServerObjectName(address[1]), "getBizCount").toString()));
                provider.setServiceCount(Integer.parseInt(jmxCollector.invoke(Constants.getRpcServerObjectName(address[1]), "getServiceCount",
                        new Object[]{service}, new String[]{String.class.getName()}).toString()));
            } catch (Exception e) {
                logger.error("{}", e);
            }
        });
        model.addAttribute("providers", providers);
    }
}
